package edu.upf.opencities.gui;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.sun.org.apache.xml.internal.security.utils.Base64;

import edu.upf.opencities.datamodel.Entry;

public class EntryManager implements Runnable{

	static Logger log = Logger.getLogger(EntryManager.class);

	private String serviceId;
	private String password;
	private Entry entry;
	private String filePath;
	
	public EntryManager(String serviceId,String password, 
								Entry entry, String filePath){
		this.serviceId = serviceId;
		this.password = password;
		this.entry = entry;
		this.filePath = filePath;
	}
	
	@Override
	public void run() {
		
		String status = sendEntry();
		System.out.println("Entry sent. RESPONSE: "+status);
		log.info("Entry sent. RESPONSE: "+status);

	}
	
	
    public String sendEntry() {


        	String credentials = serviceId+":"+password;
        	
        	
			try {
				BufferedReader br = new BufferedReader(new FileReader(filePath));
				String fileData = "";
	        	String aux;
				while ((aux = br.readLine()) != null) {
					fileData += aux + "\n";
				}
				entry.setValue(fileData);
			} catch (Exception e1) {
				return "Problems adding entry. File error: "+e1.getMessage();
			}

			

			
    		try {
	            //Now we convert the object into JSON         	
	    		Gson gson = new Gson();
	    		String jsonObj = gson.toJson(entry);
	            jsonObj = "{\"entry\":"+jsonObj+"}";
	            
	    		URL url = new URL("http://opencities.upf.edu/OSN/rest/service/addSecureEntry");
	
	            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
	            connection.setRequestMethod("POST");
	            connection.setDoInput(true);
	            connection.setDoOutput(true);
	            connection.setRequestProperty("Authorization", "Basic "+Base64.encode(credentials.getBytes()));
	            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

    		

	            //Finally we POST the JSON Object
    			DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
    			wr.write(jsonObj.getBytes("UTF-8"));
    		    wr.flush ();
    		    wr.close ();

    			int status = connection.getResponseCode();
    			//System.out.println("Status: "+status);
    			if ((status==200) || (status==201)){

    				return String.valueOf(status);
    			} else {
    				
    				return String.valueOf(status);
    			}
    		} catch (Exception e){
    			return "Problems adding entry. Network connection error: "+e.getMessage();
    			
    		}

        
        

    }



    

    
	
}
